#include "stdafx.h"
#include "MainApp.h"
#include "MainDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

BEGIN_MESSAGE_MAP(CMainApp, CWinApp)
	ON_COMMAND(ID_HELP, OnHelp)
END_MESSAGE_MAP()

CMainApp::CMainApp()
{

}

CMainApp theApp;

static UINT MainAppThread(LPVOID arg)
{
	DWORD ret;
	CMainApp *self;
	self = (CMainApp *)arg;
	while(1)
	{
		ret = ::WaitForSingleObject(self->m_hEvent, INFINITE);
		if(ret == WAIT_OBJECT_0)
		{
			if(self->m_pMainWnd)
			{
				//self->m_pMainWnd->ShowWindow(SW_NORMAL);
				self->m_pMainWnd->SetWindowPos(&CWnd::wndTop, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
				//self->m_pMainWnd->BringWindowToTop();
				//self->m_pMainWnd->SetActiveWindow();
			}
			else
			{
				TRACE("MainAppThread End\r\n");
				AfxEndThread(0);
			}
		}
	}
	return 0;
}

BOOL CMainApp::InitInstance()
{
	CWinThread *thrd;
	CWinApp::InitInstance();

	INITCOMMONCONTROLSEX InitCtrls;
	InitCtrls.dwSize = sizeof(InitCtrls);
	InitCtrls.dwICC = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);
	if(InitGlobalContex())
	{
		InitLocalContex();
		thrd = AfxBeginThread(MainAppThread, this);
		CMainDlg dlg;
		m_pMainWnd = &dlg;
		dlg.DoModal();
		m_pMainWnd = NULL;
		::SetEvent(m_hEvent);
		::WaitForSingleObject(thrd->m_hThread, INFINITE);
		::CloseHandle(m_hEvent);
	}
	return FALSE;
}

BOOL CMainApp::InitGlobalContex()
{
	LPCSTR event_name = "XCDD/HostMan";
	m_hEvent = ::OpenEvent(EVENT_ALL_ACCESS, TRUE, event_name);
	if(m_hEvent != NULL)
	{
		::SetEvent(m_hEvent);
		::CloseHandle(m_hEvent);
		return FALSE;
	}
	m_hEvent = ::CreateEventA(NULL, FALSE, FALSE, event_name);
	return (m_hEvent != NULL);
}

BOOL CMainApp::InitLocalContex()
{
	TCHAR file_name[1024];
	GetModuleFileName(NULL, file_name, 1024);
	PathRemoveFileSpec(file_name);
	SetCurrentDirectory(file_name);
	CreateDirectory(_T("etc"), NULL);
	return TRUE;
}

void CMainApp::OnHelp()
{
	ShellExecute(NULL, "open", "https://gitee.com/kerndev/HostsMan", NULL, NULL, SW_NORMAL);
}
